package com.passion.mq.rabbitmq.queue1;

import com.passion.mq.config.RabbitMqConfig;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 类描述：对应业务MQ消息处理
 *
 * @author ZhuYin
 * @since 2024年12月29日
 */
@Slf4j
@Component
@ConditionalOnBean(RabbitMqConfig.class)
public class UserOperationQueueConsumer {

    @RabbitListener(queues = "${archives.mq.business[0].queueName}", concurrency = "${archives.mq.business[0].consumerConcurrency}")
    @RabbitHandler
    public void onMessage1(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) throws IOException {
        log.info("{} onMessage() message=[{}] channel=[{}] deliveryTag=[{}]", UserOperationQueueConfig.queueName, message, channel, deliveryTag);
        try {
            // TODO business logic
            // ...

            // 处理成功，手动确认消息，一旦确认后，rabbitmq会删除掉该消息
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            log.error("{} do business exception:", UserOperationQueueConfig.queueName, e);
            // 处理失败，可以选择拒绝消息并重新入队
            channel.basicNack(deliveryTag, false, true);
        }
    }

}
